package com.frxuexi.demo.news

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.paging.filter
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.RecordEntity
import com.frxuexi.base.mvvm.BaseActivity
import com.frxuexi.demo.R
import com.frxuexi.demo.databinding.ActivityNewsBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/demo/NewsActivity")
@AndroidEntryPoint
class NewsActivity : BaseActivity<ActivityNewsBinding,NewsViewModel>() {
    lateinit var newsAdapter: NewsAdapter
    lateinit var newsPageAdapter: NewsPageAdapter
    lateinit var list: PagingData<RecordEntity>
    override fun initData() {
        lifecycleScope.launch {
            vm.newsSuccess.collect{
                if(!it.isEmpty()) {
                    Log.i("===", it.toString())
                    newsAdapter.addData(it)
                    newsAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    override fun initView() {
//        vm.getNews(1)
        newsPageAdapter= NewsPageAdapter()
        lifecycleScope.launch {
            vm.getNewsPagingData().collect{
                list=it
                newsPageAdapter.submitData(it)
            }
        }

        newsPageAdapter.setOnItemClickListener(object :OnItemClickListener{
            override fun OnItemClick(position: Int, recordEntity: RecordEntity) {
                ToastUtils.showLong("$position,"+recordEntity.title)
            }
        })

        newsPageAdapter.setOnItemLongClickListener(object :OnItemLongClickListener{
            override fun onItemLongClick(recordEntity: RecordEntity): Boolean {
                ToastUtils.showLong(recordEntity.content)
                lifecycleScope.launch {
                    list=list.filter { it != recordEntity }
                    newsPageAdapter.submitData(list)
                }
                return true
            }
        })

//        newsAdapter= NewsAdapter()
        binding.rvNews.apply {
            adapter=newsPageAdapter
            layoutManager=LinearLayoutManager(this@NewsActivity)
        }
        /*newsAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                data.removeAt(position)
                notifyItemRemoved(position)
            }
        }*/
    }
}